/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.bef.core.action.tcc;

import com.inspur.edp.bef.api.be.IBEManagerContext;
import com.inspur.edp.bef.api.be.IBusinessEntity;
import com.inspur.edp.bef.core.be.BusinessEntity;
import com.inspur.edp.bef.core.be.CoreBEContext;
import com.inspur.edp.bef.core.lock.LockService;
import com.inspur.edp.bef.core.tcc.BefTccParamItem;
import com.inspur.edp.bef.spi.entity.builtinimpls.BefModelResInfoImpl;
import com.inspur.edp.caf.transaction.api.annoation.tcc.BusinessActionContext;
import com.inspur.edp.cef.api.repository.IRootRepository;
import com.inspur.edp.cef.entity.changeset.IChangeDetail;
import com.inspur.edp.commonmodel.api.ICMManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.util.StringUtils;

public class MgrTccCancelAction {

  private final BefTccParamItem item;
  private final IBEManagerContext managerContext;
  private final BusinessActionContext tccContext;

  public MgrTccCancelAction(IBEManagerContext managerContext, BusinessActionContext tccContext,
      BefTccParamItem item) {
    this.managerContext = managerContext;
    this.tccContext = tccContext;
    this.item = item;
  }

  public void execute() throws SQLException {
    BefModelResInfoImpl modelResInfo = (BefModelResInfoImpl) managerContext.getModelResInfo();
    List<IChangeDetail> reverseChg = item.getChanges();
    if(reverseChg == null) {
      reverseChg = ((ICMManager) managerContext.getManager()).deserializeChanges(item.getChangesStr());
    }
    List<IChangeDetail> cancelChanges;
    if (modelResInfo.getAutoCancel()) {
      cancelChanges = reverseChg;
    } else {
      Date newVersion = new Date();
      if (modelResInfo.getAutoTccLock() && !StringUtils.isEmpty(item.getLockId())) {
        LockService.getInstance()
            .init4TccSecPhase(managerContext.getBEManager().getBEType(),
                item.getLockId(),
                reverseChg.stream().map(item -> item.getDataID()).collect(Collectors.toList()));
      }
      cancelChanges = new ArrayList<>(reverseChg.size());
      for (IChangeDetail change : reverseChg) {
        BusinessEntity be = (BusinessEntity) managerContext.getEntity(change.getDataID());
        be.retrieve();
        be.tccCancelByCustom(tccContext, change);
        be.getBEContext().acceptListenerChange();
      }
      for(IBusinessEntity be : managerContext.getAllEntities()) {
        if (!((BusinessEntity)be).getBEContext().hasChange()) {
          continue;
        }
        if (!be.getBEContext().isDeleted() && be.getContext().getData() != null) {
          be.setVersionControlPropValue(newVersion);
          ((CoreBEContext)be.getBEContext()).acceptListenerChange();
        }
        ((CoreBEContext)be.getBEContext()).acceptChanges();
        cancelChanges.add(be.getBEContext().getTransactionalChange());
      }
    }
    if (!cancelChanges.isEmpty()) {
      IRootRepository repo = managerContext.getBEManager().getRepository();
      repo.save(cancelChanges.toArray(new IChangeDetail[0]));
    }

    if (modelResInfo.getAutoTccLock() && !StringUtils.isEmpty(item.getLockId())) {
      LockService.getInstance().releaseTccLock(item.getLockId());
    }
  }
}
